﻿// <copyright file="DEDalUtils.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>

/////////////////////////////////////////////////////////////////////////////////////////////////
// DEDalUtils.cs - Common Data Access Layer Utilities for EDXL-DE
// Project: IC.NET SOA - IC.NET DAL
//
// Language:    C#, .NET 4.0
// Platform:    Dell XPS m1530 Windows 7, VS 2010
// Author:      Don McGarry MITRE Rome
//              dmcgarry@mitre.org, (315) 838-2669
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using EDXLCoT;
using EDXLSharp;
using EDXLSharp.CAPLib;
using EDXLSharp.EDXLDELib;
using EDXLSharp.EDXLHAVE_2_0Lib;
using EDXLSharp.EDXLRMLib;
using ICNETServices;
using MEXLSitRepLib;
using MEXLTEPLib;

namespace ICNETDAL
{
  /// <summary>
  /// A collection of utilities for working with ICNET'serializer Data Access Layer
  /// </summary>
  public static class DEDalUtils
  {
    #region Public Member Functions

    /// <summary>
    /// Converts an XML object in the GML format to the GeoRSS format.
    /// </summary>
    /// <param name="xe">the XML element containg the GML data</param>
    /// <returns>an XML element containg the GeoRSS data</returns>
    public static XElement GmltoGeoRSSSimple(XElement xe)
    {
      XmlReader xr = xe.CreateReader();
      xr.Read();
      XNamespace georss = "http://www.georss.org/georss";
      string pointstr;
      switch (xr.Name)
      {
        case "Point":
          xr.Read();
          return new XElement(georss + "point", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), xr.ReadElementContentAsString() });
        case "Polygon":
          xr.Read();
          xr.Read();
          xr.Read();
          pointstr = xr.ReadElementContentAsString();
          return new XElement(georss + "polygon", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), pointstr });
        case "LineString":
          xr.Read();

          // xr.Read();
          pointstr = xr.ReadElementContentAsString();
          return new XElement(georss + "line", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), pointstr });
        case "MultiGeometry":// Not Supported in Geo-RSS-Simple
        default:
          throw new ArgumentException("Unexpected or unsupported Name: " + xr.Name + " in DEDalUtils.GmltoGeoRSSSimple");
      }
    }

    /// <summary>
    /// This function is depricated.
    /// </summary>
    /// <param name="xe">This parameter is not used. </param>
    /// <returns>This is not used.</returns>
    public static List<XElement> GmltoGeoRSSDepricated(XElement xe)
    {
      XmlReader xr = xe.CreateReader();
      xr.Read();
      XNamespace geo = ICNETSOAConstants.DepricatedGeoRSSNS;
      List<XElement> returnval = new List<XElement>();
      xr.Read();
      string value = xr.ReadElementContentAsString();
      char[] splitchar = new char[] { ' ' };
      string[] split = value.Split(splitchar);
      returnval.Add(new XElement(geo + "lat", new object[] { new XAttribute(XNamespace.Xmlns + "geo", ICNETSOAConstants.DepricatedGeoRSSNS), split[0] }));
      returnval.Add(new XElement(geo + "long", new object[] { new XAttribute(XNamespace.Xmlns + "geo", ICNETSOAConstants.DepricatedGeoRSSNS), split[1] }));
      return returnval;
    }

    /// <summary>
    /// Converts a circle in the GML format to the GeoRSS format.
    /// </summary>
    /// <param name="circleVal">The circle, in the GML format</param>
    /// <returns>A circle in GeoRSS</returns>
    public static XElement CircletoGeoRSSSimple(string circleVal)
    {
      XNamespace georss = "http://www.georss.org/georss";
      XElement returnval = new XElement("gobble");
      returnval = new XElement(georss + "circle", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), circleVal });
      return returnval;
    }
    
    /// <summary>
    /// Swaps a pair of latitude/longitude coordinates.
    /// </summary>
    /// <param name="latLon">The latitude/longitude coordinates, in the form "X, Y"</param>
    /// <param name="replaceComma">If true, it will replace the comma in the coordinates with a space</param>
    /// <returns>The swapped latitude/longitude.</returns>
    public static string SwapLatLon(string latLon, bool replaceComma)
    {
      int index;
      string lat, lon;
      index = latLon.IndexOf(",");
      lat = latLon.Substring(0, index);
      lon = latLon.Substring(index + 1);
      if (replaceComma)
      {
        return lon + " " + lat;
      }
      else
      {
        return lon + "," + lat;
      }
    }

    /// <summary>
    /// Computes the hash value for a content object
    /// </summary>
    /// <param name="distributionID">DE Distribution ID</param>
    /// <param name="senderID">DE Sender ID</param>
    /// <param name="contentDescription">DE Content Object Content Description</param>
    /// <returns>Hash Value</returns>
    public static int ComputeHash(string distributionID, string senderID, string contentDescription)
    {
      string dscString = distributionID + senderID + contentDescription;
      byte[] data = System.Text.Encoding.ASCII.GetBytes(dscString); ;
      unchecked
      {
        const int p = 16777619;
        int hash = (int)2166136261;

        for (int i = 0; i < data.Length; i++)
          hash = (hash ^ data[i]) * p;

        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        return hash;
      }
    }

    /// <summary>
    /// Creates a "hash" out of a ValueList Urn and Value
    /// </summary>
    /// <param name="ValListUrn">ValueList Urn</param>
    /// <param name="ValListVal">ValueList Value</param>
    /// <returns>Hash Value</returns>
    public static string CreateValueListHash(string ValListUrn, string ValListVal)
    {
      return ValListUrn + "::" + ValListVal;
    }

    /// <summary>
    /// Deletes the ICNET database.
    /// </summary>
    public static void ClearCache()
    {
      EDXLSQLDataContext linqDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);
      linqDB.NukeDB();
    }

    #endregion
  }
}
